import {useQuery} from 'react-query'
import {useAPI} from './useAPI.ts'
import {useNavigate} from 'react-router-dom'

export function useConfigRoute(options?: {
  onError: (error: unknown) => void
}) {
  const api = useAPI()
  const navi = useNavigate()
  return useQuery(
    ['query-route'],
    async () => {
      const { data } = await api.getRouters()
      return data
    },
    {
      refetchOnWindowFocus: false,
      refetchOnReconnect: false,
      onSuccess(e) {
        const path = `${e.data?.[0].path}/${e.data?.[0].children?.[0].path}`
        if (path && ['/', 'auth/login'].includes(window.location.pathname)) {
          navi(path)
        }
      },
      ...options,
    },
  )
}
